// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class toggle extends cc.Component {
    @property([cc.Node])
    selectNodes: cc.Node[] = []

    // toggleGroup
    private _toggleGroup = null;
    public get toggleGroup() {
        return this._updateToggleGroup();
    }

    // 是否选中状态
    private _isSelected = false;
    private get isSelected() {
        return this.toggleGroup ? this._toggleGroup._currToggle === this : this._isSelected;
    }

    onLoad() {
        const isSelected = this.isSelected;
        this.selectNodes.forEach(node => {
            node.active = !!isSelected;
        });
    }

    start() {
        if (this.getComponent(cc.Button)) {
            this.node.on('click', this._onTouch, this);
        } else {
            this.node.on('touchend', this._onTouch, this);
        }
    }

    private _onTouch() {
        if (this.toggleGroup) {
            this._toggleGroup._toggleClickByToggle(this);
        } else {
            this._isSelected ? this.cancel() : this.select();
        }
    }

    private _updateToggleGroup() {
        let node = this.node;
        let scene = cc.director.getScene();
        this._toggleGroup = null;
        while (node.parent && node.parent !== scene) {
            this._toggleGroup = node.parent.getComponent('toggleGroup') || null;
            if (!this._toggleGroup) {
                node = node.parent;
            } else {
                break;
            }
        }
        return this._toggleGroup;
    }

    public select() {
        this._isSelected = true;
        this.selectNodes.forEach(node => {
            node.active = true;
        });
        this.node.emit('toggle', true);
    }

    public cancel() {
        this._isSelected = false;
        this.selectNodes.forEach(node => {
            node.active = false;
        });
        this.node.emit('toggle', false);
    }
}
